import { resources, Sprite, SpriteFrame, Prefab, Animation, AnimationClip, JsonAsset } from "cc";

export class ResourceManager {

    static spriteFrames = new Map();
    static animations = new Map();

    static init({ preload }) {

        // 预加载
        const { spriteFrame, prefab } = preload;

        // 精灵贴图
        if (spriteFrame && spriteFrame.length > 0) {
            spriteFrame.forEach((_path: string) => {
                resources.preloadDir(_path, SpriteFrame);
            });
        }

        // 预制体
        if (prefab && prefab.length > 0) {
            prefab.forEach((_path: string) => {
                resources.preloadDir(_path, Prefab);
            });
        }
    }

    static setSpriteFrame(_sprite: Sprite, _name: string) {
        resources.load(_name + "/spriteFrame", SpriteFrame, (_err, _asset) => {
            _sprite.spriteFrame = _asset;
        });
    }

    static setAnimationClip(_animation: Animation, _name: string) {
        resources.load(_name, (_err, _clip: AnimationClip) => {
            _animation.addClip(_clip);
        });
    }

    static setPrefabs(_path: string, _name: string, _callback: Function) {
        resources.load(`${_path}/${_name}`, (_err, _p: Prefab) => {
            if (!_err) {
                _callback(_p);
            }
            _callback();
        });
    }

    static getJsonData(_path: string, _name: string, _callback: Function) {
        resources.load(`${_path}/${_name}`, (_err, _json: JsonAsset) => {
            if (!_err) {
                _callback(_json.json);
            }
            _callback();
        });
    }
}